<?php
namespace Core\Service;

use Core\Exception as CoreException;
use Phalcon\Di\Injectable;

class Api extends Injectable
{
    public function register() {
        $modules = $this->app->getModules();
        foreach ($modules as $moduleName => $module) {
            // Initialize module api.
            $this->di->setShared(
                strtolower($moduleName),
                function () use ($moduleName) {
                    return new Class($moduleName) extends Injectable{

                        protected $_module;

                        public function __construct($module) {
                            $this->_module = $module;
                        }

                        public function __call($name, $arguments) {
                            $apiClassName = sprintf('%s\Api\%s', ucfirst($this->_module), ucfirst($name));
                            if (!$this->di->has($apiClassName)) {
                                if (!class_exists($apiClassName)) {
                                    $msg = sprintf('Can not find Api with name "%s".', $name);
                                    throw new CoreException($msg);
                                }

                                $api = new $apiClassName($arguments);
                                $this->di->set($apiClassName, $api, true);
                                return $api;
                            }
                            return $this->di->get($apiClassName);
                        }
                    };
                }
            );
        }
        return $this;
    }
}